<template>
  <div>
    <el-card class="top-operation-card" v-show="showSearch">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="108px">
        <el-form-item label="排班计划名称" prop="workPlanName">
          <el-input v-model="queryParams.workPlanName" placeholder="请输入排班计划名称" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="plan-table-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['task:plan:add']">新增</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button
            type="plain"
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['task:plan:edit']"
            >修改</el-button
          >
        </el-col> -->
        <el-col :span="1.5">
          <el-button type="plain" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
            v-hasPermi="['task:plan:remove']">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="plain" icon="el-icon-download" size="mini" @click="handleExport"
            v-hasPermi="['task:plan:export']">导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange" :max-height="500">
        <el-table-column type="selection" width="55" align="left" />
        <el-table-column type="expand">
          <template slot-scope="props">
            <div style="display: flex; flex-wrap: wrap">
              <div style="
                  width: 150px;
                  padding: 5px;
                  margin-left: 5px;
                  margin-bottom: 5px;
                " :class="!item.detailStatus
                  ? 'no-plan'
                  : item.detailStatus == 1
                    ? 'work-plan'
                    : 'rest-plan'
                  " v-for="(item, index) in props.row.planDetailList" :key="index">
                <div style="text-align: center; font-weight: bold">
                  {{ item.effectDate }}
                </div>
                <div style="padding: 16px 0 12px; text-align: center" v-if="!item.detailStatus">
                  暂无排班
                </div>
                <div style="padding-top: 10px" v-else-if="item.detailStatus == 1 && item.spanDetail">
                  <div style="
                      padding-bottom: 5px;
                      font-size: 10px;
                      text-align: center;
                    " v-for="(itemSpan, indexSpan) in item.spanDetail.split(',')" :key="indexSpan">
                    {{ itemSpan }}
                  </div>
                </div>
                <div v-else style="padding: 16px 0 12px; text-align: center">
                  <i class="iconfont el-icon-rest"></i>
                  休假
                </div>
                <div style="text-align: center; padding-bottom: 5px" v-if="item.enabled == 1">
                  <el-button size="mini" type="text" icon="el-icon-plus"
                    @click="tableAddTeam(item, props.$index, index)">添加班组</el-button><el-button size="mini" type="text"
                    icon="el-icon-basketball" @click="tableRestDay(item)">休假</el-button>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="60" align="left" />
        <el-table-column label="人员" align="left" prop="personName" />
        <el-table-column label="所属部门单位" align="left" prop="deptName" width="220" />

        <el-table-column label="排班计划名称" align="left" prop="workPlanName" />

        <el-table-column label="备注" align="left" prop="remark" />
        <el-table-column label="创建时间" align="left" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="left" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="scope">
            <!-- <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['task:plan:edit']"
              >修改</el-button
            > -->
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['task:plan:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </el-card>

    <!-- 添加或修改排班计划对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="1000px" append-to-body top="10px">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="排班计划名称" prop="workPlanName">
              <el-input v-model="form.workPlanName" placeholder="请输入排班计划名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划时间">
              <el-radio-group v-model="calendarMonth" @change="changeCalendarMonth">
                <el-radio label="本月"></el-radio>
                <el-radio label="下月"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="16">
          <el-col :span="12">
           <el-form-item label="所属单位" prop="companyId">
              <el-select
                v-model="form.companyId"
                placeholder="请选择所属单位"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in companyOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item> 
           
          </el-col>
          <el-col :span="12"> </el-col>
        </el-row> -->

        <el-form-item label="工作对象名称" prop="persons">
          <div @click="addPersons" style="
              background-color: #ffffff;
              background-image: none;
              border: 1px solid #dcdfe6;
              border-radius: 4px;
              height: 100px;
              padding: 0 5px;
            ">
            <el-tag size="small" closable v-for="(item, index) in form.persons" :key="index"
              @close="removePerson(index)">{{ item.personName }}</el-tag>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>

        <!-- 里面写eleCalendar组件-->
        <ele-calendar :defaultValue="defaultDateValue" :highlight="false" :disabledDate="disabledData"
          :render-content="renderContent" :data="datedef" :prop="prop" border
          style="height: 380px; overflow-y: scroll"></ele-calendar>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--添加人员-->
    <personDialog :visible.sync="personDialogVisible" :hasSelect="form.persons" @changePersons="getSelectedPersons" />
    <!--添加班组-->
    <teamDialog :visible.sync="teamDialogVisible" :teamType="addTeamType" @changeTableTeam="getSelectedTeamTable"
      @changeFormTeam="getSelectedTeamForm" />
  </div>
</template>

<script>
import {
  listPlan,
  getPlan,
  delPlan,
  addPlan,
  updatePlan,
  exportPlan,
} from "@/api/task/plan";
import { updateDetail } from "@/api/task/detail";
import eleCalendar from "@/components/ele-calendar";
// import "ele-calendar/dist/vue-calendar.css"; //引入css
import personDialog from "./personDialog";
import teamDialog from "./teamDialog";

import dayjs from "dayjs";

export default {
  name: "Plan",
  components: {
    eleCalendar,
    personDialog,
    teamDialog,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 排班计划表格数据
      planList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        workPlanName: null,
        workPlanType: "person",
      },
      // 表单参数
      form: {
        persons: [],
      },
      // 表单校验
      rules: {
        fenceId: [
          { required: true, message: "所属作业区域必选", trigger: "change" },
        ],
        workPlanName: [
          { required: true, message: "排班计划名称不能为空", trigger: "blur" },
        ],
        workType: [
          { required: true, message: "工作类型必选", trigger: "change" },
        ],

        persons: [
          {
            required: true,
            message: "工作对象名称必选",
            trigger: "change",
            type: "array",
          },
        ],
      },
      personDialogVisible: false,
      teamDialogVisible: false,
      addTeamType: "table",
      planDetail: null, //table 内增加排班和休假
      rowIndex: 0, //正在修改table的第几行
      spanDetailIndex: 0, //正在修改哪一个日期
      datedef: [],
      currOperateDate: null, //当前操作的日期
      prop: "date", //对应日期字段名
      calendarMonth: "本月", //日期所选的时间范围
      defaultDateValue: "",
    };
  },
  computed: {
    deptId() {
      return this.$store.getters.choosedDeptId;
    },
  },

  watch: {
    deptId: function () {
      this.queryParams.deptId = this.deptId;
      this.getList();
    },
    calendarMonth(value) {
      if (value == "本月") {
        this.defaultDateValue = new Date();
      } else {
        this.defaultDateValue = dayjs(new Date()).add(1, "month").date(1);
      }
    },
  },
  // computed: {
  //   defaultDateValue() {
  //     if (this.calendarMonth == "本月") {
  //       return new Date();
  //     } else {
  //       return dayjs(new Date()).add(1, "month").date(1);
  //     }
  //   },
  // },
  created() {
    this.getList();

    this.getFullMonthArr();
  },
  methods: {
    /** 查询排班计划列表 */
    getList() {
      this.loading = true;
      this.queryParams.deptId = this.deptId;

      listPlan(this.queryParams).then((response) => {
        this.planList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        workPlanId: null,
        workPlanName: null,
        deptId: null,
        fenceId: null,
        workType: null,
        objectIds: null,
        objectNames: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        persons: [],
        planMonth: null,
        deptId: this.deptId,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.workPlanId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加排班计划";
      this.datedef = [];
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const workPlanId = row.workPlanId || this.ids;
      getPlan(workPlanId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改排班计划";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.workPlanId != null) {
            updatePlan(this.form).then((response) => {
              if (response.code === 200) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            let params = JSON.parse(JSON.stringify(this.form));
            params.workPlanType = "person";
            params.personIds = params.persons
              .map((v) => {
                return v.personId;
              })
              .join(",");
            let tempPlanDetailList = this.datedef.map((v) => {
              return {
                workTeamId: v.workTeamId,
                effectDate: dayjs(v.date).format("YYYY-MM-DD"),
                detailStatus: v.detailStatus,
              };
            });
            let dayArr = this.getFullMonthArr();
            let planDetailList = [];
            dayArr.forEach((v) => {
              let index = tempPlanDetailList.findIndex(
                (item) => item.effectDate == v.effectDate
              );
              if (index == -1) {
                planDetailList.push(v);
              } else {
                planDetailList.push(tempPlanDetailList[index]);
              }
            });
            params.planMonth = planDetailList[0].effectDate.substring(0, 7);

            params.planDetailList = planDetailList;
            addPlan(params).then((response) => {
              if (response.code === 200) {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    getFullMonthArr() {
      /*获取一个月的天数 */

      let countDays = 0;

      if (this.calendarMonth == "本月") {
        countDays = dayjs(new Date())
          .add(1, "month")
          .date(1)
          .subtract(1, "day").$D;
      } else {
        countDays = dayjs(new Date())
          .add(2, "month")
          .date(1)
          .subtract(1, "day").$D;
      }

      var dayArr = [];

      for (var k = 1; k <= countDays; k++) {
        dayArr.push({
          workTeamId: null,
          effectDate:
            this.calendarMonth == "本月"
              ? dayjs(new Date().setDate(k)).format("YYYY-MM-DD")
              : dayjs(new Date()).add(1, "month").date(k).format("YYYY-MM-DD"),
          detailStatus: 0,
        });
      }
      return dayArr;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const workPlanIds = row.workPlanId || this.ids;
      this.$confirm(
        '是否确认删除人员"' + (row.personName || "已勾选") + '"的排班?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delPlan(workPlanIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(function () { });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有排班计划数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportPlan(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        })
        .catch(function () { });
    },
    /** 弹出添加人员table */
    addPersons() {
      this.personDialogVisible = true;
    },
    getSelectedPersons(selectedRows) {
      this.form.persons = selectedRows;
    },
    removePerson(index) {
      this.form.persons.splice(index, 1);
    },
    changeCalendarMonth() {
      this.datedef = [];
    },
    disabledData(time) {
      let startDay = null;
      let endDay = null;
      if (this.calendarMonth == "本月") {
        startDay = dayjs(new Date()).hour(0).minute(0).second(0).$d;
        endDay = dayjs(new Date())
          .add(1, "month")
          .date(1)
          .subtract(1, "day")
          .hour(1)
          .minute(0)
          .second(0).$d; //下下个月第一天
      } else {
        startDay = dayjs(new Date())
          .add(1, "month")
          .date(1)
          .subtract(1, "day")
          .hour(1)
          .minute(0)
          .second(0).$d;
        endDay = dayjs(new Date())
          .add(2, "month")
          .date(1)
          .subtract(1, "day")
          .hour(1)
          .minute(0)
          .second(0).$d;
      }

      return (
        time.getTime() > endDay.getTime() || time.getTime() < startDay.getTime()
      );
    },
    renderContent(h, params) {
      let todayDate = new Date().getDate();
      if (this.calendarMonth == "本月") {
      } else {
        todayDate = 0;
      }

      let showTxt = h("div", {
        style: {
          lineHeight: "60px",
        },
      });
      if (params.defvalue.value && params.defvalue.value.detailStatus == 1) {
        showTxt = h(
          "div",
          {},
          params.defvalue.value.showTxt.map(function (v, index) {
            return h("div", {}, v);
          })
        );
      }

      const loop = (data) => {
        return data.defvalue.type == "normal" &&
          data.defvalue.text > todayDate ? (
          <div>
            <div style="line-height:40px;">{data.defvalue.text}</div>
            {showTxt}
            {data.defvalue.value && data.defvalue.value.detailStatus == 2 ? (
              <div style="line-height:60px;">
                <i class="iconfont el-icon-rest"></i>
              </div>
            ) : (
              ""
            )}

            <div style="line-height:40px;">
              <el-tooltip content="复制昨天" placement="top">
                <el-button
                  icon="el-icon-document-copy"
                  circle
                  size="mini"
                  onClick={this.copyYesterday.bind(this, data.defdate)}
                  style="padding:4px"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="清空" placement="top">
                <el-button
                  icon="el-icon-delete"
                  circle
                  size="mini"
                  onClick={this.clearDate.bind(this, data.defdate)}
                  style="padding:4px"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="添加班组" placement="top">
                <el-button
                  icon="el-icon-plus"
                  circle
                  size="mini"
                  onClick={this.addTeam.bind(this, data.defdate)}
                  style="padding:4px"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="休假" placement="top">
                <el-button
                  icon="el-icon-basketball"
                  circle
                  size="mini"
                  onClick={this.restDay.bind(this, data.defdate)}
                  style="padding:4px"
                ></el-button>
              </el-tooltip>
            </div>
          </div>
        ) : (
          <div>
            <div>{data.defvalue.text}</div>
          </div>
        );
      };
      return <div>{loop(params)}</div>;
    },
    addTeam(defdate) {
      this.addTeamType = "form";

      this.teamDialogVisible = true;
      this.currOperateDate = defdate;
    },
    getSelectedTeamForm(team) {
      let index = this.datedef.findIndex(
        (v) => v.date.getTime() == this.currOperateDate.getTime()
      );
      if (index == -1) {
        this.datedef.push({
          date: this.currOperateDate,
          workTeamId: team.workTeamId,
          detailStatus: 1,
          showTxt: team.teamSpanList.map((v) => {
            return `${v.teamSpanName} ${v.startSpan}-${v.endSpan}`;
          }),
        });
      } else {
        this.datedef[index] = {
          date: this.currOperateDate,
          workTeamId: team.workTeamId,
          detailStatus: 1,
          showTxt: team.teamSpanList.map((v) => {
            return `${v.teamSpanName} ${v.startSpan}-${v.endSpan}`;
          }),
        };
      }
    },
    copyYesterday(defdate) {
      let yesterday = new Date(defdate.getTime() - 24 * 60 * 60 * 1000);
      let index = this.datedef.findIndex(
        (v) => v.date.getTime() == yesterday.getTime()
      );
      if (index > -1) {
        let currIndex = this.datedef.findIndex(
          (v) => v.date.getTime() == defdate.getTime()
        );
        if (currIndex == -1) {
          this.datedef.push({
            date: defdate,
            workTeamId: this.datedef[index].workTeamId,
            detailStatus: this.datedef[index].detailStatus,
            showTxt: this.datedef[index].showTxt,
          });
        } else {
          this.datedef[currIndex] = {
            date: defdate,
            workTeamId: this.datedef[index].workTeamId,
            detailStatus: this.datedef[index].detailStatus,
            showTxt: this.datedef[index].showTxt,
          };
        }
      } else {
        this.$modal.msgError("昨日没有计划");
      }
    },
    clearDate(defdate) {
      let index = this.datedef.findIndex(
        (v) => v.date.getTime() == defdate.getTime()
      );
      if (index > -1) {
        this.datedef.splice(index, 1);
      } else {
      }
    },
    restDay(defdate) {
      let index = this.datedef.findIndex(
        (v) => v.date.getTime() == defdate.getTime()
      );
      if (index == -1) {
        this.datedef.push({
          date: defdate,
          workTeamId: null,
          detailStatus: 2,
        });
      } else {
        this.datedef[index] = {
          date: defdate,
          workTeamId: null,
          detailStatus: 2,
        };
      }
    },
    tableAddTeam(detail, rowIndex, spanDetailIndex) {
      this.addTeamType = "table";
      this.teamDialogVisible = true;
      this.planDetail = detail;
      this.rowIndex = rowIndex;
      this.spanDetailIndex = spanDetailIndex;
    },
    getSelectedTeamTable(team) {
      this.planDetail.detailStatus = 1;
      this.planDetail.spanDetail = team.teamSpanList
        .map((v) => {
          return `${v.teamSpanName} (${v.startSpan}-${v.endSpan})`;
        })
        .join(",");
      this.planDetail.workTeamId = team.workTeamId;
      this.planDetail.workTeamName = team.workTeamName;
      updateDetail(this.planDetail).then((response) => {
        if (response.code === 200) {
          this.$modal.msgSuccess("增加排班成功");
          this.planList[this.rowIndex].planDetailList[this.spanDetailIndex] =
            this.planDetail;
          // this.getList();
        }
      });
    },
    tableRestDay(detail) {
      detail.workTeamId = null;
      detail.detailStatus = 2;
      updateDetail(detail).then((response) => {
        if (response.code === 200) {
          this.$modal.msgSuccess("休假成功");
          // this.getList();
        }
      });
    },
  },
};
</script>
<style lang="scss">
.el-picker-panel-calendar__icon-btn {
  display: none;
}

.no-plan {
  background: rgba(200, 200, 200, 0.1);
  border: 1px solid #737373;
}

.rest-plan {
  background: rgba(82, 196, 26, 0.1);
  border: 1px solid #52c41a;
}

.work-plan {
  background: rgba(31, 132, 235, 0.1);
  border: 1px solid #1f84eb;
}
</style>
